package com.chen.shopping_file_service.service;

import com.chen.shopping_common.result.BusException;
import com.chen.shopping_common.result.CodeEnum;
import com.chen.shopping_common.service.FileService;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

@DubboService
public class FileServiceImpl implements FileService {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Value("${fdfs.fileUrl}")
    private String fileUrl;

    @Override
    public String uploadImage(byte[] fileBytes, String fileName) {

            if(fileBytes != null){
                try{
                    //将字节数组转化为输入流
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
                    //获取文件的后缀名
                    String fileSuffix = fileName.substring(fileName.lastIndexOf(".")+1);
                    //上传文件
                    /**
                    * inputStream.available()输入流的字节总数
                    */
                    StorePath storePath = fastFileStorageClient.uploadFile(inputStream, inputStream.available(), fileSuffix, null);
                    //返回文件的路径
                    return fileUrl+"/"+storePath.getFullPath();
                }catch(Exception e){
                    throw new BusException(CodeEnum.UPLOAD_FILE_ERROR);
                }
            }else {
                throw new BusException(CodeEnum.UPLOAD_FILE_ERROR);
            }




    }

    //删除文件
    @Override
    public void delete(String filePath) {
        fastFileStorageClient.deleteFile(filePath);
    }
}
